package yunjiao.javatutorials.guava.base.pairwise;

import com.google.common.base.Equivalence;

import java.util.Arrays;
import java.util.List;

/**
 * 实际使用示例
 *
 * @author yangyunjiao
 */
public class PairwiseEquivalenceExample {
    public static void main(String[] args) {
        // 创建基于字符串长度比较的 Equivalence
        Equivalence<String> lengthEquivalence = new Equivalence<String>() {
            @Override
            protected boolean doEquivalent(String a, String b) {
                if (a == null && b == null) return true;
                if (a == null || b == null) return false;
                System.out.println("a=" + a + ", b=" + b);
                return a.length() == b.length();
            }

            @Override
            protected int doHash(String s) {
                return s != null ? s.length() : 0;
            }
        };

        // 创建 PairwiseEquivalence
        Equivalence<Iterable<String>> pairwiseByLength = lengthEquivalence.pairwise();

        // 测试数据
        List<String> list1 = Arrays.asList("apple", "banana", "cherry");
        List<String> list2 = Arrays.asList("fruit", "yellow", "cherry");
        List<String> list3 = Arrays.asList("apple", "banana");

        // 比较列表
        System.out.printf("list1=%s 和 list2=%s 等价: %b \n", list1.toString(), list2.toString(),
                pairwiseByLength.equivalent(list1, list2)); // true
        System.out.printf("list1=%s 和 list3=%s 等价: %b \n", list1.toString(), list3.toString(),
                pairwiseByLength.equivalent(list1, list3)); // false

        // 计算哈希值
        System.out.println("list1 哈希值: " + pairwiseByLength.hash(list1));
        System.out.println("list2 哈希值: " + pairwiseByLength.hash(list2));
    }
}
